package com.woniuxy.juc.writeandread;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO:
 * <P> Date: 2022/4/11:18:39
 * <P> Description:
 */
@Slf4j(topic = "c.c")
@SuppressWarnings("all")
public class WriteAndReadLock {
    public static void main(String[] args) throws InterruptedException {
        DataContainer dc = new DataContainer();
        new Thread(()->{
            dc.read();
        },"t1").start();

        Thread.sleep(100);
        new Thread(()->{
            dc.read();
        },"t2").start();
    }
}

@Slf4j(topic = "c.c")
class DataContainer {

    private Object data;

    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();

    private ReentrantReadWriteLock.ReadLock r = rw.readLock();

    private ReentrantReadWriteLock.WriteLock w = rw.writeLock();

    public Object read() {
        log.debug("获取读锁");
        r.lock();

        try {
            log.debug("读...");
            Sleep.sleep(1L);
            return data;
        } finally {
            log.debug("释放读锁");
            r.unlock();
        }

    }

    public void write() {
        log.debug("获取写锁");
        w.lock();
        try {
            log.debug("写入");
        } finally {
            log.debug("释放写锁");
            w.unlock();
        }

    }


}
